import { AxiosProgressEvent } from 'axios';

import {
  DatasetListItem,
  CollectionListRes,
  DatasetListReq,
  DatasetUpdateReq,
  DatasetCreateReq,
  CollectionPreviewInfoRes,
  CollectionListReq,
  CollectionReadReq,
  CollectionReadRes,
  CreateDatasetCollectionReq,
  UpdateDatasetCollectionRes,
  FcsTaskDatasetRes,
  AllWebLinkRes,
  FolderCreateReq,
  CreateDatasetItemnReq,
  PaginationResponse,
  GetDatasetDataListProps,
  CollectionIndexReq,
  InsertFaqReq,
  InsertFaqRes,
  InsertDataReq,
  KnowledgeReq,
  CreateKnowledgeReq,
  KnowledgeListReq,
  DatasetDeleteReq,
  KnowledgeListRes,
  uploadFileReq,
  UpdateFileReq,
} from '@/common/types';
import { CreateApiCollectionReq, FcsRewareHousingReq } from '@/types/api';

import apiClient from '../apiClient';
import {
  AddCollectionMetadataType,
  DatasetCollectionSchemaType,
  DatasetDataListItemType,
  DelCollectionMetadataType,
} from '@/types/dataset';
import { ParentIdType, ParentTreePathItemType } from '@/types/workflow/node';
import { IgnoreListReq } from '@/types/know/know';

export enum DatasetApi {
  DatasetDetail = '/api/ruigpt/main/dataset/detail',

  // FastDatasetList = '/api/ruigpt/main/dataset/list',
  DatasetList = '/openapi/v1/dataset',
  AllDatasetList = '/api/ruigpt/main/dataset/allDataset',

  DatasetCreate = '/api/ruigpt/main/dataset/build',
  DatasetCreateFromRuigpt = '/openapi/v1/dataset/create',
  DatasetUpdate = '/api/ruigpt/main/dataset/modify',
  DatasetDelete = '/openapi/v2/dataset/delete',
  DatasetDeleteApi = '/openapi/v1/dataset/delete/api',

  // folder
  FolderCreate = '/api/ruigpt/main/dataset/folder/build',

  // Api
  // 创建API数据
  CreateApiCollection = '/openapi/v1/dataset/collection/create/api',

  // fcs文件进度查询接口
  FcsTaskDataset = '/fcs/openapi/v1/task/dataset',
  FcsTaskDeleta = '/fcs/openapi/v1/task/delete',
  //http://172.30.232.99:30888/api/openapi/v1/fcs/rewarehousing
  // 重新入库
  FcsRewareHousing = '/openapi/v1/fcs/rewarehousing',

  // url
  AllWebLink = '/webcrawl/openapi/v1/get_all_web_link',
  WebUrlTaskDelete = '/webcrawl/openapi/v1/delete',
  WeburlTaskStatus = '/webcrawl/openapi/v1/task_status',
  WeburlChildStatus = '/webcrawl/openapi/v1/get_child_url_info',
  WeburlTaskRetry = '/webcrawl/openapi/v1/retry',
  WeburlTaskStop = '/webcrawl/openapi/v1/stop_task',

  // v2/list
  DatasetDataV2List = '/api/core/dataset/data/v2/list',
  ApiDataV2List = '/openapi/v1/dataset/collection/detail/',
  DelDatasetData = '/api/ruigpt/main/dataset/information/remove',

  CollectionList = '/api/ruigpt/main/dataset/collection/list',
  CollectionRead = '/api/ruigpt/main/dataset/collection/read',

  // 发布知识库
  KnowledgeBasePublish = '/openapi/v2/dataset/checklist/publish',

  // 获取collection详情
  CollectionDetail = '/openapi/v1/dataset/collection/detail',
  AddCollectionMetadata = '/openapi/v1/dataset/collection/metadata',
  DelCollectionMetadata = '/openapi/v1/dataset/collection/metadata/delete',

  // 添加数据集索引
  AddCollectionIndex = '/openapi/v1/dataset/collection/index',
  DelCollectionIndex = '/openapi/v1/dataset/collection/index',

  //更新api数据集数据
  updateCollectionApi = '/openapi/v1/dataset/collection/api',
  // updateCollectionApi = '/openapi/v1/dataset/data/api',

  // 数据集chunks
  CollectionDatas = '/openapi/v1/dataset/collection/datas',
  //更新chunk数据
  CollectionDataUpdate = '/api/ruigpt/main/dataset/information/modify',

  // 文件预览
  CollectionPreviewInfo = '/openapi/v1/dataset/collection',

  //入库
  UploadCollection = '/api/ruigpt/shared/document/upload',
  CreateDatasetItem = '/api/ruigpt/main/dataset/collection/build',
  CreateDatasetCollection = '/api/ruigpt/main/dataset/collection/build/fileId',
  CreateCsvCollection = '/api/ruigpt/main/dataset/collection/build/csvTable',
  CollectionLink = '/api/ruigpt/main/dataset/collection/build/link',
  DeleteDatasetCollection = '/api/ruigpt/main/dataset/collection/remove',
  UpdateDatasetCollection = '/api/ruigpt/main/dataset/collection/modify',

  // UpdateDatesetData = '/openapi/v1/dataset/data/api',
  UpdateDatesetData = '/openapi/v1/dataset/collection/update/api',
  CreateDatesetData = '/openapi/v1/dataset/collection/create/api',

  // faq入库
  InsertFaq = '/openapi/v1/dataset/data/faq',
  // 插入chunk
  InsertData = '/api/ruigpt/main/dataset/information/insertData',
  // 创建faq库
  CreateFaqDataset = '/openapi/v1/dataset/data/faq/create',

  //知识库审批列表
  KnowledgeBaseApprovalList = '/openapi/v2/dataset/checklist',
  // 知识库审核历史
  KnowledgeBaseApprovalListHistory = '/openapi/v2/dataset/checklist/history',
  //通过 / 驳回  处理接口
  KnowledgeBaseApprovalStatus = '/openapi/v2/dataset/checklist/status',

  //选择知识库
  KnowledgeBaseSelect = '/openapi/v2/groups',
  //创建知识库
  CreateKnowledgeBase = '/openapi/v2/dataset/create',
  //查询知识库
  GetDatasetList = '/openapi/v2/dataset/datasetlist',
  //更新知识库
  UpdateKnowledgeBase = '/openapi/v2/dataset/update',
  //获取组下用户
  GetGroupUser = '/openapi/v2/users',

  GetDatasetPaths = '/api/core/dataset/paths',
  //查看文档类型
  DocumentTypeList = '/openapi/v2/dataset/type/list',
  //查看知识库下的文件列表
  GetDatasetFileList = '/openapi/v2/dataset/filelist',

  //知识库文件上传
  UploadFile = '/openapi/v2/proxy/import',

  //启用和停用
  SetForBid = '/openapi/v2/dataset/file/forbid',
  //删除知识库下文件
  DeleteDatasetFile = '/openapi/v2/dataset/delete/file',
  //修改知识库下文档
  UpdateDatasetFile = '/openapi/v2/proxy/file/update',

  // V2移动文件
  UpdateFile = '/openapi/v2/proxy/move/update',

  //删除知识库审批下的文档
  DeleteApprovalDocument = '/openapi/v2/dataset/review/delete',
  //重新审批
  ReviewApprovalDocument = '/openapi/v2/dataset/checklist/review',

  // 鉴权配置
  BusinessAuth = '/openapi/v2/dataset/{appId}/business/auth',
  //查看文档内容
  GetCheckList = '/openapi/v2/knowledges/optimize/checklist/list'
}

/**
 * 获取知识库
 * @param data 获取知识库请求参数
 * @returns
 */
// const datasetList = (data: DatasetListReq) => apiClient.post<DatasetListItem[]>(
//   { url: DatasetApi.DatasetList, data }
// );
const datasetList = (data: DatasetListReq) =>
  apiClient.post<DatasetListItem[]>({ url: DatasetApi.DatasetList, data });

const allDatasetList = (data: DatasetListReq) =>
  apiClient.post<DatasetListItem[]>({ url: DatasetApi.AllDatasetList, data });

const datasetCreate = (data: DatasetCreateReq) =>
  apiClient.post({ url: DatasetApi.DatasetCreate, data });
const datasetCreateFromRuigpt = (data: DatasetCreateReq) =>
  apiClient.post({ url: DatasetApi.DatasetCreateFromRuigpt, data });
const datasetUpdate = (data: DatasetUpdateReq) =>
  apiClient.post({ url: DatasetApi.DatasetUpdate, data });
const datasetDelete = (data: DatasetDeleteReq) =>
  apiClient.post({ url: DatasetApi.DatasetDelete, data });
const getBusinessAuth = (appId: string, datasetId?: string) => {
  let url = `${DatasetApi.BusinessAuth.replace('{appId}', appId)}`
  if (datasetId) {
    url += `?datasetId=${datasetId}`
  }
  return apiClient.get({ url });
}
const updateBusinessAuth = (appId: string, data: DatasetDeleteReq) =>
  apiClient.post({ url: `${DatasetApi.BusinessAuth.replace('{appId}', appId)}`, data });

const datasetDeleteApi = (data: DatasetDeleteReq) =>
  apiClient.post({ url: DatasetApi.DatasetDeleteApi, data });

//查看文档内容
const getCheckList = (params: { appId: string, collectionId: string }) =>
  apiClient.get({ url: DatasetApi.GetCheckList, params });


// folder
const folderCreate = (data: FolderCreateReq) =>
  apiClient.post({ url: DatasetApi.FolderCreate, data });

/**
 * 获取指定知识库详情
 * @param id 知识库id
 * @returns
 */
const getDatasetDetail = (id: string) =>
  apiClient.get<DatasetListItem>({ url: `${DatasetApi.DatasetDetail}`, params: { id } });

/**
 *
 * @param data 获取知识库
 * @returns
 */
const collectionList = (data: CollectionListReq) =>
  apiClient.post<CollectionListRes>({ url: DatasetApi.CollectionList, data });

/**
 *
 * @param data 获取chunk
 * @returns
 */
const datasetDataV2List = (data: GetDatasetDataListProps) =>
  apiClient.post<PaginationResponse<DatasetDataListItemType>>({
    url: DatasetApi.DatasetDataV2List,
    data,
  });

/**
* 获取数据接口详细信息
* @param collectionId 
* @returns
*/
const apiDataV2List = (collectionId: string) =>
  apiClient.get({
    url: DatasetApi.ApiDataV2List + collectionId,
  });

/**
 * 删除chunk
 * @param data
 * @returns
 */
const delDatasetData = (id: string) =>
  apiClient.delete({
    url: DatasetApi.DelDatasetData,
    params: { id },
  });

/**
 *
 * @param data 获取文件下载地址
 * @returns
 */
const collectionRead = (data: CollectionReadReq) =>
  apiClient.get<CollectionReadRes>({ url: DatasetApi.CollectionRead, params: data });

/**
 * 获取collection详情
 * @param id
 * @returns
 */
const collectionDetail = (id: string) =>
  apiClient.get<DatasetCollectionSchemaType>({ url: DatasetApi.CollectionDetail + `/${id}` });

/**
 * 添加/更新collection元数据
 * @param data
 * @returns
 */
const addCollectionMetadata = (data: AddCollectionMetadataType) =>
  apiClient.post({ url: DatasetApi.AddCollectionMetadata, data });

/**
 * 删除collection元数据
 * @param data
 * @returns
 */
const delCollectionMetadata = (data: DelCollectionMetadataType) =>
  apiClient.post({ url: DatasetApi.DelCollectionMetadata, data });

/**
 * 获取collection chunks数据
 * @param id
 * @returns
 */
const getCollectionDatas = (params: GetDatasetDataListProps) =>
  apiClient.get<PaginationResponse<DatasetDataListItemType>>({
    url: DatasetApi.CollectionDatas,
    params,
  });

/**
 * 更新collection chunks数据
 * @param id
 * @returns
 */
const updateCollectionData = (data: DatasetDataListItemType) =>
  apiClient.put({
    url: DatasetApi.CollectionDataUpdate,
    data,
  });

/**
 * 添加数据集索引
 * @param data
 * @returns
 */
const addCollectionIndex = (data: CollectionIndexReq) =>
  apiClient.post({ url: DatasetApi.AddCollectionIndex, data });

/**
 * 删除数据集索引
 * @param data
 * @returns
 */
const delCollectionIndex = (params: CollectionIndexReq) =>
  apiClient.delete({ url: DatasetApi.AddCollectionIndex, params });

/**
 * 更新数据集数据
 * @param data
 * @returns
 */
const updateCollectionApi = (payload: {
  data_id: string | number;
  functionSchema: Record<string, any>;
}) =>
  apiClient.put({
    url: `${DatasetApi.updateCollectionApi}/${payload.data_id}`,
    data: { functionSchema: payload.functionSchema }, // 请求体数据放在data字段
  });

const updateDatesetData = (payload: {
  datasetId: string | number;
  id: string;
  name: string,
  functionSchema: Record<string, any>;
  headerAuth?: Object;
}) =>
  apiClient.post({
    url: `${DatasetApi.UpdateDatesetData}`,
    data: { functionSchema: payload.functionSchema, id: payload.id, name: payload.name, datasetId: payload.datasetId, headerAuth: payload.headerAuth }, // 请求体数据放在data字段
  });

const createDatesetData = (payload: {
  datasetId: string | number;
  appId: string;
  name: string,
  functionSchema: Record<string, any>;
  headerAuth?: Object;
}) =>
  apiClient.post({
    url: `${DatasetApi.CreateDatesetData}`,
    data: { functionSchema: payload.functionSchema, appId: payload.appId, name: payload.name, datasetId: payload.datasetId, headerAuth: payload.headerAuth }, // 请求体数据放在data字段
  });

/**
 * @param data 文件预览信息
 * @returns
 */
const collectionPreviewInfo = (data: CollectionReadReq) =>
  apiClient.get<CollectionPreviewInfoRes>({ url: DatasetApi.CollectionPreviewInfo, params: data });

const postUploadFiles = (
  data: FormData,
  onUploadProgress: (progressEvent: AxiosProgressEvent) => void,
  signal?: AbortSignal,
) =>
  apiClient.post({
    url: DatasetApi.UploadCollection,
    withCredentials: true,
    timeout: 600000,
    data,
    onUploadProgress,
    headers: { 'Content-Type': 'multipart/form-data' },
    signal,
  });

const createDatasetCollection = (data: CreateDatasetCollectionReq) =>
  apiClient.post({ url: DatasetApi.CreateDatasetCollection, data, timeout: 600000 });

const createApiCollection = (data: CreateApiCollectionReq) =>
  apiClient.post({ url: DatasetApi.CreateApiCollection, data });

const createDatasetItem = (data: CreateDatasetItemnReq) =>
  apiClient.post({ url: DatasetApi.CreateDatasetItem, data });

const createCsvCollection = (data: CreateDatasetCollectionReq) =>
  apiClient.post({ url: DatasetApi.CreateCsvCollection, data, timeout: 600000 });

const createCollectionLink = (data: CreateDatasetCollectionReq) =>
  apiClient.post({ url: DatasetApi.CollectionLink, data, timeout: 600000 });

const deleteDatasetCollection = (id: string) =>
  apiClient.delete({ url: DatasetApi.DeleteDatasetCollection, params: { id } });

const updateDatasetCollection = (data: UpdateDatasetCollectionRes) =>
  apiClient.post({ url: DatasetApi.UpdateDatasetCollection, data });


/** *
 * 获取fcs文件导入状态
 */
const getFcsTaskDataset = (dataset_id: string) =>
  apiClient.get<FcsTaskDatasetRes[]>({
    url: DatasetApi.FcsTaskDataset,
    params: { dataset_id, file_source: 'local' },
  });

/** *
 * 删除fcs文件导入任务
 */
const deleteFcsTaskDelete = (file_id: string) =>
  apiClient.post({ url: DatasetApi.FcsTaskDeleta, data: { file_id } });

/**
 * 重新入库
 * @param data
 */
const postFcsRewareHousing = (data: FcsRewareHousingReq) => {
  apiClient.post({ url: DatasetApi.FcsRewareHousing, data });
};

/** *
 * 获取web导入状态
 */
const getAllWebLink = (datasetId: string, pageNum: number, pageSize: number) =>
  apiClient.get<AllWebLinkRes>({
    url: DatasetApi.AllWebLink,
    params: { datasetId, pageNum, pageSize },
  });

/** *
 * 删除网站爬取任务进度
 */
const deleteUrlTaskDelete = (crawl_records_id: string) =>
  apiClient.delete({ url: DatasetApi.WebUrlTaskDelete, params: { crawl_records_id } });

// const deleteUrlTaskDelete = (crawl_records_id: string) => apiClient.delete(
//   { url: DatasetApi.WebUrlTaskDelete, params: { crawl_records_id } }
// );

// const deleteUrlTaskDelete = (crawl_records_id: string) => apiClient.delete(
//   { url: DatasetApi.WebUrlTaskDelete, params: { crawl_records_id } }
// );

const weburlTaskStop = (crawl_records_id: string) =>
  apiClient.get({ url: DatasetApi.WeburlTaskStop, params: { crawl_records_id } });

const weburlTaskResume = (crawl_records_id: string) =>
  apiClient.get({ url: DatasetApi.WeburlTaskRetry, params: { crawl_records_id } });

const getWeburlTaskStatus = (id: string) =>
  apiClient.get({ url: `${DatasetApi.WeburlTaskStatus}/${id}` });

const getWeburlChildStatus = (id: string, page: number, pageSize: number) =>
  apiClient.get({
    url: `${DatasetApi.WeburlChildStatus}?crawl_records_id=${id}&pageNum=${page}&pageSize=${pageSize}`,
  });

/**
 * 向 统一FAQ数据集 添加QA问答对
 * @param data
 * @returns
 */
const insertFaq = (data: InsertFaqReq) =>
  apiClient.post<InsertFaqRes>({ url: DatasetApi.InsertFaq, data });

/**
 * 插入chunk数据
 * @param data
 * @returns
 */
const insertData = (data: InsertDataReq) => apiClient.post({ url: DatasetApi.InsertData, data });

/**
 * 创建faq库
 * @param name
 * @returns
 */
const createFaqDataset = (name: string, appId: string) =>
  apiClient.post({ url: DatasetApi.CreateFaqDataset, data: { name, appId } });

const getDatasetPaths = (parentId: ParentIdType) =>
  apiClient.get<ParentTreePathItemType[]>({
    url: DatasetApi.GetDatasetPaths,
    params: { parentId },
  });

/**
 * 知识库审批列表
 * @param name
 * @returns
 */
const knowledgeBaseApprovalList = (params: KnowledgeReq) =>
  apiClient.get({ url: DatasetApi.KnowledgeBaseApprovalList, params });
/**
 * 知识库审核历史
 * @param name
 * @returns
 */
const knowledgeBaseApprovalListHistory = (params: KnowledgeReq) =>
  apiClient.get({ url: DatasetApi.KnowledgeBaseApprovalListHistory, params });
/**
 * 知识库通过，驳回
 * @param name
 * @returns
 */
const knowledgeBaseApprovalStatus = (data: KnowledgeReq) =>
  apiClient.put({ url: DatasetApi.KnowledgeBaseApprovalStatus, data });

/**
 * 选择知识库
 * @param name
 * @returns
 */
const knowledgeBaseSelect = (params: KnowledgeReq) =>
  apiClient.get({ url: DatasetApi.KnowledgeBaseSelect + `/${params.id}` });
/**
 * 获取组下面的所有用户
 * @param name
 * @returns
 */
const getGroupUser = (params: KnowledgeReq) =>
  apiClient.get({ url: DatasetApi.GetGroupUser, params });

/**
 * 创建知识库
 * @param name
 * @returns
 */
const createKnowledgeBase = (data: CreateKnowledgeReq) =>
  apiClient.post({ url: DatasetApi.CreateKnowledgeBase, data });

/**
 * 创建知识库
 * @param name
 * @returns
 */
const updateKnowledgeBase = (data: CreateKnowledgeReq) =>
  apiClient.post({ url: DatasetApi.UpdateKnowledgeBase, data });
/**
 * 查询知识库
 * @param name
 * @returns
 */
const getDatasetList = (params: KnowledgeListReq) =>
  apiClient.get<KnowledgeListRes>({ url: DatasetApi.GetDatasetList, params });
/**
 * 查看文档类型
 * @param name
 * @returns
 */
const documentTypeList = (params: KnowledgeListReq) =>
  apiClient.get({ url: DatasetApi.DocumentTypeList, params });
/**
 * 查看知识库下的文件列表
 * @param name
 * @returns
 */
const getDatasetFileList = (params: KnowledgeListReq) =>
  apiClient.get({ url: DatasetApi.GetDatasetFileList, params });
/**
 * 查看知识库下的文件列表
 * @param name
 * @returns
 */
// const uploadFile = (data: uploadFileReq) =>
//   apiClient.post({ url: DatasetApi.UploadFile, data });

const uploadFile = (
  data: FormData,
  onUploadProgress: (progressEvent: AxiosProgressEvent) => void,
  signal?: AbortSignal,
) =>
  apiClient.post({
    url: DatasetApi.UploadFile,
    withCredentials: true,
    timeout: 600000,
    data,
    onUploadProgress,
    headers: { 'Content-Type': 'multipart/form-data' },
    signal,
  });

/**
 * 知识库发布
 * @param app_id
 * @returns
 */
const knowledgeBasePublish = (data: { app_id: string }) =>
  apiClient.post({ url: DatasetApi.KnowledgeBasePublish, data: { ...data } });
/**
 * 启用和停用
 * @param {fileId: string, forbid: boolean}
 * @returns
 */
const setForBid = (data: { id: string; forbid: boolean }) =>
  apiClient.post({ url: DatasetApi.SetForBid, data });
/**
 * 删除知识库下文件
 * @param fileId
 * @returns
 */
const deleteDatasetFile = (data: { ids: string[], batchList?: IgnoreListReq[] }) =>
  apiClient.post({ url: DatasetApi.DeleteDatasetFile, data });
/**
 * 修改知识库下文件
 * @param {id:string name:string}
 * @returns
 */
const updateDatasetFile = (data: { id: string; name: string }) =>
  apiClient.post({ url: DatasetApi.UpdateDatasetFile, data });

/**
 * @description: 移动文件
 * @return {*}
 */
const updateFile = (data: UpdateFileReq) => apiClient.post({ url: DatasetApi.UpdateFile, data });

/**
 * @description: 删除审批下文档
 * @return {*}
 */
const deleteApprovalDocument = (data: { ids: string[], appId: string, }) => apiClient.post({ url: DatasetApi.DeleteApprovalDocument, data });
/**
 * @description: 重新审批
 * @return {*}
 */
const reviewApprovalDocument = (data: KnowledgeReq) => apiClient.post({ url: DatasetApi.ReviewApprovalDocument, data });

export default {
  datasetList,
  allDatasetList,
  datasetUpdate,
  datasetCreate,
  datasetCreateFromRuigpt,
  datasetDelete,
  getBusinessAuth,
  updateBusinessAuth,
  folderCreate,
  getDatasetDetail,
  collectionList,
  collectionRead,
  postUploadFiles,
  createDatasetItem,
  createDatasetCollection,
  createCsvCollection,
  deleteDatasetCollection,
  updateDatasetCollection,
  createCollectionLink,
  collectionPreviewInfo,
  getFcsTaskDataset,
  deleteFcsTaskDelete,
  postFcsRewareHousing,
  getAllWebLink,
  deleteUrlTaskDelete,
  getWeburlTaskStatus,
  getWeburlChildStatus,
  weburlTaskStop,
  weburlTaskResume,
  createApiCollection,
  datasetDataV2List,
  apiDataV2List,
  delDatasetData,
  collectionDetail,
  addCollectionMetadata,
  delCollectionMetadata,
  addCollectionIndex,
  delCollectionIndex,
  getCollectionDatas,
  insertFaq,
  insertData,
  createFaqDataset,
  updateCollectionData,
  updateCollectionApi,
  updateDatesetData,
  createDatesetData,
  getDatasetPaths,
  knowledgeBaseApprovalList,
  knowledgeBaseApprovalListHistory,
  knowledgeBaseApprovalStatus,
  knowledgeBaseSelect,
  createKnowledgeBase,
  getGroupUser,
  getDatasetList,
  updateKnowledgeBase,
  documentTypeList,
  getDatasetFileList,
  uploadFile,
  knowledgeBasePublish,
  setForBid,
  deleteDatasetFile,
  updateDatasetFile,
  updateFile,
  deleteApprovalDocument,
  datasetDeleteApi,
  reviewApprovalDocument,
  getCheckList,
};
